package controllers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.ini4j.Ini;

import others.ExecuteCommande;
import variables.VarConfigInt;

public class ActionConcatVideoListener implements ActionListener {

	protected Ini configIni;
	protected JFrame frame;
	
	
	public ActionConcatVideoListener(Ini configIni, JFrame frame) {
		this.configIni = configIni;
		this.frame = frame;
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		File directory = new File(this.configIni.get(
				VarConfigInt.CONFIG_SECTION_PATH,
				VarConfigInt.CONFIG_VAR_PATH_MOVIES));
		;
		String outputDirectory = this.configIni.get(
				VarConfigInt.CONFIG_SECTION_PATH,
				VarConfigInt.CONFIG_VAR_PATH_DEST);
		String ffmpeg = this.configIni.get(
				VarConfigInt.CONFIG_SECTION_SOFTWARE,
				VarConfigInt.CONFIG_VAR_SOFTWARE_FFMPEG);

		JFileChooser chooser = new JFileChooser(directory);
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
				"Videos files", "avi", "mkv", "wmv", "mp4", "m4v");
		chooser.setFileFilter(filter);
		chooser.setMultiSelectionEnabled(true);
		int returnVal = chooser.showOpenDialog(this.frame);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File[] files = chooser.getSelectedFiles();
			for (int i = 0; i < files.length; i++) {
				new ExecuteCommande(ffmpeg + " -i "
						+ files[i].getAbsolutePath() + " -qscale:v 1 "
						+ outputDirectory + "intermediate_part"
						+ (i + 1) + ".mpg").run();
			}

			String temp = "";
			for (int i = 1; i < files.length + 1; i++) {
				if (i == 1)
					temp += outputDirectory + "intermediate_part" + i
							+ ".mpg";
				else
					temp += "|" + outputDirectory + "intermediate_part"
							+ i + ".mpg";
			}
			new ExecuteCommande(ffmpeg + " -i concat:" + temp
					+ " -c copy " + outputDirectory
					+ "intermediate_all.mpg").run();
			new ExecuteCommande(ffmpeg + " -i " + outputDirectory
					+ "intermediate_all.mpg -qscale:v 2 "
					+ outputDirectory + "output.avi");

			temp = "rm -rf ";
			for (int i = 1; i < files.length + 1; i++) {
				temp += outputDirectory + "intermediate_part" + i
						+ ".mpg ";
			}
			temp += outputDirectory + "intermediate_all.mpg";
			System.out.println(temp);
			// new ExecuteCommande(temp).run();
		}
	}

}
